﻿using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using Newtonsoft.Json;
using Web.Account;

namespace AssetManage.Handler
{
    public class Account : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext currentContext)
        {
            var action = currentContext.Request.Params["action"];
            var userid = currentContext.Request.Params["userid"];
            var tableid = currentContext.Request.Params["tableid"];
            var currentpassword = currentContext.Request.Params["currentpassword"];
            var newpassword = currentContext.Request.Params["newpassword"];
            var password = currentContext.Request.Params["password"];
            var captcha = currentContext.Request.Params["captcha"];
            var email = currentContext.Request.Params["email"];
            var emailcaptcha = currentContext.Request.Params["emailcaptcha"];
            var realname = currentContext.Request.Params["realname"];

            var responseJsonStringBuilder = new StringBuilder();
            var responseJsonStringWriter = new StringWriter(responseJsonStringBuilder);

            JsonWriter responseJsonWriter = new JsonTextWriter(responseJsonStringWriter);
            responseJsonWriter.Formatting = Formatting.Indented;
            responseJsonWriter.WriteStartObject();

            switch (action)
            {
                case "verify":
                    if (!AccountManage.IsExistUserID(userid))
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("UserID_Error");
                        break;
                    }
                    if (AccountManage.VerifyAccount(userid, password))
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(true);
                    }
                    else
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("Password_Error");
                    }
                    break;
                case "login":
                    if (currentContext.Request.Cookies["ASP.NET_SessionId"] == null)
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("Cookie_Error");
                        break;
                    }
                    if (
                        !String.Equals(currentContext.Session["CAPTCHA"].ToString(), captcha,
                            StringComparison.CurrentCultureIgnoreCase))
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("Captcha_Error");
                        break;
                    }
                    if (!AccountManage.IsExistUserID(userid))
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("UserID_Error");
                        break;
                    }

                    if (AccountManage.VerifyAccount(userid, password))
                    {
                        var role = "User";
                        if (AccountManage.IsAdministrator(userid))
                        {
                            role = "Administrator";
                        }
                        HttpContext.Current.Session.Abandon();
                        var ticket = new FormsAuthenticationTicket(
                            1,
                            userid,
                            DateTime.Now,
                            DateTime.Now.AddMinutes(60),
                            false,
                            role,
                            FormsAuthentication.FormsCookiePath
                            );
                        var encryptTicket = FormsAuthentication.Encrypt(ticket);
                        var newCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptTicket);
                        HttpContext.Current.Response.Cookies.Add(newCookie);

                        if (HttpContext.Current.Request.IsAuthenticated)
                        {
                            HttpContext.Current.Response.Redirect("~/Error/Cookie", false);
                            responseJsonWriter.WritePropertyName("success");
                            responseJsonWriter.WriteValue(false);
                            responseJsonWriter.WritePropertyName("error");
                            responseJsonWriter.WriteValue("Cookie_Error");
                        }
                        else
                        {
                            responseJsonWriter.WritePropertyName("success");
                            responseJsonWriter.WriteValue(true);
                        }
                    }
                    else
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("Password_Error");
                    }
                    break;
                case "create":
                    if (String.IsNullOrEmpty(tableid))
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("TableID_Error");
                        break;
                    }
                    if (String.IsNullOrEmpty(realname))
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("RealName_Error");
                        break;
                    }
                    if (AccountManage.IsExistTableID(tableid))
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("TableID_IsExist");
                        break;
                    }
                    if (AccountManage.CreateTable(tableid))
                    {
                        if (AccountManage.CreateAccount(tableid, realname))
                        {
                            responseJsonWriter.WritePropertyName("success");
                            responseJsonWriter.WriteValue(true);
                        }
                        else
                        {
                            responseJsonWriter.WritePropertyName("success");
                            responseJsonWriter.WriteValue(false);
                            responseJsonWriter.WritePropertyName("error");
                            responseJsonWriter.WriteValue("Server_Error");
                            AccountManage.DeleteTable(tableid);
                        }
                    }
                    else
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("Server_IsExist");
                    }
                    break;
                case "delete":
                    if (String.IsNullOrEmpty(tableid))
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("TableID_Error");
                        break;
                    }
                    if (!AccountManage.IsExistTableID(tableid))
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("TableID_IsNotExist");
                        break;
                    }
                    if (AccountManage.DeleteAccount(tableid))
                    {
                        if (AccountManage.DeleteTable(tableid))
                        {
                            responseJsonWriter.WritePropertyName("success");
                            responseJsonWriter.WriteValue(true);
                        }
                        else
                        {
                            responseJsonWriter.WritePropertyName("success");
                            responseJsonWriter.WriteValue(false);
                            responseJsonWriter.WritePropertyName("error");
                            responseJsonWriter.WriteValue("Server_Error");
                        }
                    }
                    else
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("Server_IsExist");
                    }
                    break;
                case "regist":
                    if (currentContext.Request.Cookies["ASP.NET_SessionId"] == null)
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("Cookie_Error");
                        break;
                    }
                    if (
                        !String.Equals(currentContext.Session["CAPTCHA"].ToString(), captcha,
                            StringComparison.CurrentCultureIgnoreCase))
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("Captcha_Error");
                        break;
                    }
                    if (AccountManage.IsExistUserID(userid))
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("UserID_IsExist");
                        break;
                    }
                    if (String.IsNullOrEmpty(password) || password.Length != 64)
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("Password_Error");
                        break;
                    }
                    if (String.IsNullOrEmpty((String) currentContext.Session["EMAIL_CAPTCHA"]) &&
                        currentContext.Session["EMAIL_CAPTCHA"].ToString() != emailcaptcha)
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("EmailCaptcha_Error");
                        break;
                    }
                    if (!Regex.IsMatch(email, @"^(\w)+(\.\w+)*@(\w)+((\.\w{2,3}){1,3})$"))
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("Email_Error");
                        break;
                    }
                    if (AccountManage.IsExistEmail(email))
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("Email_IsExist");
                        break;
                    }
                    if (AccountManage.RegistAccount(userid, tableid, password, email))
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(true);
                    }
                    else
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("Create_Error");
                    }
                    break;
                case "balance":
                    if (String.IsNullOrEmpty(tableid))
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("TableID_Error");
                        break;
                    }
                    var accountBalance = AccountManage.GetBalance(tableid);
                    responseJsonWriter.WritePropertyName("success");
                    responseJsonWriter.WriteValue(true);
                    responseJsonWriter.WritePropertyName("balance");
                    responseJsonWriter.WriteValue(accountBalance.ToString("0.00"));
                    if (accountBalance >= 0)
                    {
                        responseJsonWriter.WritePropertyName("color");
                        responseJsonWriter.WriteValue("#3c763d");
                    }
                    else
                    {
                        responseJsonWriter.WritePropertyName("color");
                        responseJsonWriter.WriteValue("#a94442");
                    }
                    break;
                case "changepassword":
                    userid = currentContext.User.Identity.Name;
                    if (String.IsNullOrEmpty(newpassword) || newpassword.Length != 64)
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("NewPassword_Error");
                        return;
                    }

                    if (String.IsNullOrEmpty(newpassword) || currentpassword.Length != 64)
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("CurrentPassword_Error");
                        return;
                    }
                    if (AccountManage.VerifyAccount(userid, currentpassword))
                    {
                        if (AccountManage.ChangePassword(userid, newpassword))
                        {
                            responseJsonWriter.WritePropertyName("success");
                            responseJsonWriter.WriteValue(true);
                            FormsAuthentication.SignOut();
                            HttpContext.Current.Session.Abandon();
                            HttpContext.Current.Request.Cookies.Clear();
                        }
                        else
                        {
                            responseJsonWriter.WritePropertyName("success");
                            responseJsonWriter.WriteValue(false);
                            responseJsonWriter.WritePropertyName("error");
                            responseJsonWriter.WriteValue("Server_Error");
                        }
                    }
                    else
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("CurrentPassword_Error");
                    }
                    break;
                case "resetpassword":
                    if (currentContext.Session["CAPTCHA"].ToString().ToUpper() != captcha.ToUpper())
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("Captcha_Error");
                        break;
                    }
                    if (String.IsNullOrEmpty((String) currentContext.Session["EMAIL_CAPTCHA"]) &&
                        currentContext.Session["EMAIL_CAPTCHA"].ToString() != emailcaptcha)
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("EmailCaptcha_Error");
                        break;
                    }
                    if (!Regex.IsMatch(email, @"^(\w)+(\.\w+)*@(\w)+((\.\w{2,3}){1,3})$"))
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("Email_Error");
                        break;
                    }
                    if (!AccountManage.IsExistEmail(email))
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("Email_IsNotExist");
                        break;
                    }
                    userid = AccountManage.GetUserID(email);
                    if (!AccountManage.IsExistUserID(userid))
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("UserID_IsNotExist");
                        break;
                    }
                    if (String.IsNullOrEmpty(password) || password.Length != 64)
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("Password_Error");
                        break;
                    }
                    if (AccountManage.ChangePassword(userid, password))
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(true);
                    }
                    else
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("ResetPassword_Error");
                    }
                    break;
            }
            responseJsonWriter.WriteEndObject();
            currentContext.Response.Write(responseJsonStringBuilder.ToString());
        }

        public bool IsReusable
        {
            get { return false; }
        }
    }
}